/**     
* @Title: UserServiceImpl.java   
* @Package com.xnkf.server.service.impl   
* @Description: TODO   
* @author xaoyaoyao
* @date 2017年10月20日 下午11:07:59
*/
package com.xnkf.server.service.impl;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xnkf.common.subject.UserInfo;
import com.xnkf.common.util.Constants;
import com.xnkf.common.util.RetResult;
import com.xnkf.common.util.SessionUtils;
import com.xnkf.common.util.TokenUtils;
import com.xnkf.server.entity.User;
import com.xnkf.server.mgr.UserMgr;
import com.xnkf.server.service.UserService;

/**
 * @ClassName: UserServiceImpl
 * @Description: TODO
 * @author xaoyaoyao
 * @date 2017年10月20日 下午11:07:59
 * 
 */
@Service
public class UserServiceImpl implements UserService {

	private final static Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);

	@Autowired
	private UserMgr userMgr;

	@Override
	public RetResult login(String name, String passwd) {
		RetResult retResult = new RetResult();
		if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(passwd)) {
			User user = userMgr.findByNameAndPasswd(name, passwd);
			if (null != user) {
				String authcToken = TokenUtils.generateAuthcToken(user.getId(), true);
				UserInfo info = new UserInfo();
				info.setAuthcToken(authcToken);
				info.setUserId(user.getId() + "");
				info.setName(name);
				SessionUtils.setAuthcToken(authcToken);
				SessionUtils.setUser(info);
				retResult.addData(Constants.PROPERTY_COMMON_DATA_KEY, info);
				return retResult;
			}
		}
		retResult.setCode(1000);
		retResult.setMsg("用户名或密码有误");
		return retResult;
	}

	@Override
	public RetResult registration(String name, Integer age, String passwd) {
		RetResult retResult = new RetResult();
		User u = userMgr.findByName(name);
		if (null != u) {
			retResult.setCode(1002);
			retResult.setMsg("注册失败，此用户已存在");
			return retResult;
		}
		try {
			User user = new User();
			user.setAge(age);
			user.setName(name);
			user.setPasswd(passwd);
			userMgr.save(user);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			retResult.setCode(1001);
			retResult.setMsg("注册失败");
		}
		return retResult;
	}

	@Override
	public RetResult queryName(String name) {
		RetResult retResult = new RetResult();
		retResult.addData(Constants.PROPERTY_COMMON_DATA_KEY, userMgr.findByName(name));
		return retResult;
	}
}
